package com.citytechinc.cmis.client.service
{
	import com.citytechinc.cmis.client.event.DocumentEvent;
	import com.citytechinc.cmis.client.model.Folder;
	import com.citytechinc.cmis.util.Encoder;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.filesystem.File;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	import flash.net.URLRequestMethod;
	
	public class DocumentService extends EventDispatcher
	{
		private namespace app = "http://www.w3.org/2007/app";
		private namespace atom = "http://www.w3.org/2005/Atom";
		private namespace cmis = "http://www.cmis.org/2008/05";
		
		use namespace app;
        use namespace atom;
        use namespace cmis;
        
		private var auth:String;
		
		public function DocumentService(auth:String)
		{
			this.auth = auth;
		}
		
		public function createDocument(folder:Folder, file:File):void 
		{
			var content:String = Encoder.getString(file);
			
			var msg:XML = 
				<entry xmlns="http://www.w3.org/2005/Atom" xmlns:cmis="http://www.cmis.org/2008/05">
					<title>{file.name}</title>
					<content type="application/octet-stream">{content}</content>
					<cmis:object>
						<cmis:properties>
							<cmis:propertyString cmis:name="ObjectTypeId"><cmis:value>document</cmis:value></cmis:propertyString>
						</cmis:properties>
					</cmis:object>
				</entry>
			
			var request:URLRequest = new URLRequest(folder.childrenURL);

			request.data = msg;
			request.contentType = "application/atom+xml;type=entry";
			request.method = URLRequestMethod.POST;
			
			var header:URLRequestHeader = new URLRequestHeader("Authorization", "Basic " + auth);
            
            request.requestHeaders.push(header);

			var loader:URLLoader = new URLLoader();

			loader.addEventListener(Event.COMPLETE, this.dispatchEvent);
			loader.load(request);
		}

	}
	
}